package com.sky.service.impl;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sky.entity.futu.Account;
import com.sky.entity.futu.FutuResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

@Service
@Slf4j
public class FutuAccountService {

    private final OkHttpClient okHttpClient;
    private final Gson gson = new Gson();
    @Value("${futu.base-url}")
    private String BASE_URL;
    private final String prefix = "/account"; // 替换为Python API的URL

    // 拼接 BASE_URL 和 prefix
    private String getBaseUrlWithPrefix() {
        return BASE_URL + prefix;
    }

    @Autowired
    public FutuAccountService(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    private Object executeRequest(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 解析响应体为Map，具体实现可根据需要调整
            return parseResponse(response.body().string()).getData();
        }
    }

    private FutuResponse parseResponse(String responseBody) {
        return gson.fromJson(responseBody, FutuResponse.class); // 替换为实际解析
    }

    public List<Account> getAccountList() throws IOException {
        String url = getBaseUrlWithPrefix() + "/list";
        Object jsonResponse = executeRequest(url); // 假设executeRequest返回的是JSON字符串
        log.info("jsonResponse:{}", jsonResponse);

        // 解析JSON为List<Account>
        // 创建并返回AccountList对象
        return gson.fromJson(gson.toJson(jsonResponse), new TypeToken<List<Account>>() {
        }.getType());
    }

    // todo 锁定或解锁交易

/*    public T getHistoryDeals(String code, String start, String end) throws IOException {
        String url = String.format(BASE_URL + "/api/deal/deals?code=%s&start=%s&end=%s", code, start, end);
        return executeRequest(url, null);
    }
*/
}
